<template>
  <div class="app-container">
    <el-form
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
        class="el-form-search"
    >
      <el-form-item label="类型" prop="type" class="el-form-search-item">
        <el-select
            v-model="queryParams.type"
            placeholder="请选择类型"
            clearable
            size="default"
        >
          <el-option
              v-for="(item, index) in typeOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state" class="el-form-search-item">
        <el-select
            v-model="queryParams.state"
            placeholder="请选择状态"
            clearable
            size="default"
        >
          <el-option label="待审核" value="0"></el-option>
          <el-option label="待出租" value="1"></el-option>
          <el-option label="已出租" value="2"></el-option>
          <el-option label="已下架" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="el-form-search-item">
        <el-button
            type="primary"
            icon="search"
            size="default"
            @click="handleQuery"
        >搜索</el-button
        >
        <el-button icon="refresh" size="default" @click="resetQuery"
        >重置</el-button
        >
        <right-toolbar
            v-model:showSearch="showSearch"
            @setDataTable="setDataTable"
            :columns="columns"
        ></right-toolbar>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb5">
      <el-col :span="1.5">
        <el-button
          plain
          icon="plus"
          size="default"
          @click="handleAdd"
          v-hasPermi="['system:houseRoom:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="edit"
          size="default"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:houseRoom:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          icon="delete"
          size="default"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:houseRoom:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-dropdown
          size="medium"
          @command="(command) => handleImportCommand(command)"
        >
          <el-button plain icon="caret-bottom" size="default"
            >数据导入</el-button
          >
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="handleImport" icon="upload"
              >数据导入</el-dropdown-item
              >
              <el-dropdown-item command="handleExport" icon="download"
              >数据导出</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown
          size="medium"
          @command="(command) => handleMoreCommand(command)"
          v-hasPermi="['system:houseRoom:more']"
        >
          <el-button
            plain
            icon="caret-bottom"
            size="default"
            :disabled="multiple"
            v-hasPermi="['system:houseRoom:more']"
            >更多功能</el-button
          >
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="handleAgent" icon="setting"
              >设置经纪人</el-dropdown-item
            >
            <el-dropdown-item command="handleAudit" icon="check"
              >审核房源</el-dropdown-item
            >
            <el-dropdown-item command="handlePush" icon="lock"
              >出租房源</el-dropdown-item
            >
            <el-dropdown-item command="handleClose" icon="close"
              >下架房源</el-dropdown-item
            >
            <el-dropdown-item command="handleOpen" icon="check"
              >上架房源</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-table
      :height="tableHeight"
      v-loading="loading"
      :data="houseRoomList"
      @selection-change="handleSelectionChange"
      ref="dataTableRef"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="#" type="index" width="50" align="center">
        <template #default="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="类型"
        align="center"
        prop="type"
        :formatter="typeFormatter"
        width="60"
        :key="columns[0].key"
        v-if="columns[0].visible"
      >
      </el-table-column>
      <el-table-column
        label="户型"
        align="center"
        prop="houseCode"
        width="120"
        :key="columns[1].key"
        v-if="columns[1].visible"
      />
      <el-table-column
        label="整套面积"
        align="center"
        prop="houseArea"
        width="80"
        :key="columns[2].key"
        v-if="columns[2].visible"
      />
      <el-table-column
        label="出租房间"
        align="center"
        prop="roomType"
        :formatter="roomTypeFormatter"
        width="80"
        :key="columns[3].key"
        v-if="columns[3].visible"
      ></el-table-column>
      <el-table-column
        label="房屋面积"
        align="center"
        prop="roomArea"
        width="80"
        :key="columns[4].key"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="朝向"
        align="center"
        prop="direction"
        width="60"
        :key="columns[5].key"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="装修"
        align="center"
        prop="decoration"
        width="80"
        :key="columns[6].key"
        v-if="columns[6].visible"
      />
      <el-table-column
        label="租金"
        align="center"
        prop="price"
        width="60"
        :key="columns[7].key"
        v-if="columns[7].visible"
      />
      <el-table-column
        label="起租日期"
        align="center"
        prop="startDate"
        width="100"
        :key="columns[8].key"
        v-if="columns[8].visible"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.startDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="状态"
        align="center"
        prop="state"
        width="60"
        :formatter="stateFormatter"
        :key="columns[9].key"
        v-if="columns[9].visible"
      />
      <el-table-column
        label="封面图"
        align="center"
        prop="faceUrl"
        width="80"
        :key="columns[10].key"
        v-if="columns[10].visible"
      >
        <template #default="scope">
          <image-preview :src="scope.row.faceUrl" :width="30" :height="30" />
        </template>
      </el-table-column>
      <el-table-column
        label="小区名称"
        align="center"
        prop="villageName"
        :show-overflow-tooltip="true"
        width="180"
        :key="columns[11].key"
        v-if="columns[11].visible"
      />
      <el-table-column
        label="房牌号"
        align="center"
        prop="houseNo"
        :show-overflow-tooltip="true"
        width="90"
        :key="columns[13].key"
        v-if="columns[13].visible"
      />
      <el-table-column
        label="门牌号"
        align="center"
        prop="roomCode"
        width="80"
        :key="columns[12].key"
        v-if="columns[12].visible"
      />
      <el-table-column
        label="房源代号"
        align="center"
        prop="code"
        width="90"
        :key="columns[14].key"
        v-if="columns[14].visible"
      ></el-table-column>
      <el-table-column
        label="房东姓名"
        align="center"
        prop="ownerName"
        width="100"
        :key="columns[17].key"
        v-if="columns[17].visible"
      />
      <el-table-column
        label="房东电话"
        align="center"
        prop="owerPhone"
        width="100"
        :key="columns[18].key"
        v-if="columns[18].visible"
      />
      <el-table-column
        label="经纪人"
        align="center"
        prop="agentName"
        width="70"
        :key="columns[15].key"
        v-if="columns[15].visible"
      />
      <el-table-column
        label="经纪人电话"
        align="center"
        prop="agentPhone"
        width="100"
        :key="columns[16].key"
        v-if="columns[16].visible"
      />
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        width="80"
        :show-overflow-tooltip="true"
        :key="columns[19].key"
        v-if="columns[19].visible"
      />
      <el-table-column
        fixed="right"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template #default="scope">
          <el-button
            size="default"
            type="text"
            icon="edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:houseRoom:edit']"
            >修改</el-button
          >
          <el-button
            size="default"
            type="text"
            icon="delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:houseRoom:remove']"
            >删除</el-button
          >
          <el-button
            size="default"
            type="text"
            icon="view"
            @click="evalList(scope.row)"
            v-hasPermi="['system:evaluate:list']"
            >评价</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改房源详情对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="800px"
      append-to-body
      destroy-on-close
      @close="reset"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="请选择类型"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in typeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="居室" prop="houseNum">
              <el-select
                v-model="form.houseNum"
                placeholder="请选择居室"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in houseNumOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12"
            ><el-form-item label="厅室" prop="houseHall">
              <el-select
                v-model="form.houseHall"
                placeholder="请选择厅室"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in houseHallOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12"
            ><el-form-item label="卫生间" prop="toiletNum">
              <el-select
                v-model="form.toiletNum"
                placeholder="请选择卫生间"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in toiletNumOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="整套面积" prop="houseArea">
              <el-input v-model="form.houseArea" placeholder="请输入整套面积" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出租房间" prop="roomType">
              <el-select
                v-model="form.roomType"
                placeholder="请选择出租房间"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in roomTypeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="房屋面积" prop="roomArea">
              <el-input v-model="form.roomArea" placeholder="请输入房屋面积" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="朝向" prop="direction">
              <el-select
                v-model="form.direction"
                placeholder="请选择朝向"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in directionOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="装修" prop="decoration">
              <el-select
                v-model="form.decoration"
                placeholder="请选择装修"
                clearable
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in decorationOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="租金" prop="price">
              <el-input v-model="form.price" placeholder="请输入租金" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="起租日期" prop="startDate">
              <el-date-picker
                clearable
                size="small"
                v-model="form.startDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择起租日期"
                style="width: 100%"
              >
              </el-date-picker> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="房源描述" prop="introduce">
              <el-input
                v-model="form.introduce"
                placeholder="请输入房源描述"
                :autosize="{ minRows: 2, maxRows: 2 }"
                :style="{ width: '100%' }"
              ></el-input> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="房源小区" prop="villageId">
              <el-select
                v-model="form.villageId"
                placeholder="请选择房源小区"
                clearable
                :style="{ width: '100%' }"
                @change="changeVillage"
              >
                <el-option
                  v-for="(item, index) in houseVillageList"
                  :key="index"
                  :label="item.name"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入详细地址"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="房牌号" prop="houseNo">
              <el-input v-model="form.houseNo" placeholder="请输入房牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门牌号" prop="roomCode">
              <el-input v-model="form.roomCode" placeholder="请输入门牌号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="房东姓名" prop="ownerName">
              <el-input
                v-model="form.ownerName"
                placeholder="请输入房东姓名"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="房东电话" prop="owerPhone">
              <el-input
                v-model="form.owerPhone"
                placeholder="请输入房东电话"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input
                v-model="form.longitude"
                placeholder="请输入经度 longitude"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input
                v-model="form.latitude"
                placeholder="请输入纬度 latitude"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入备注"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="房源亮点" prop="featureList">
              <el-checkbox-group v-model="featureList">
                <el-checkbox label="看房方便"></el-checkbox>
                <el-checkbox label="独卫"></el-checkbox>
                <el-checkbox label="独立阳台"></el-checkbox>
                <el-checkbox label="智能锁"></el-checkbox>
                <el-checkbox label="可短租"></el-checkbox>
                <el-checkbox label="首次出租"></el-checkbox>
                <el-checkbox label="免物业费"></el-checkbox>
                <el-checkbox label="民用水电"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="房源图片" prop="imageList">
              <image-upload v-model="imageList" :limit="9" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-row :gutter="30">
          <el-col :span="24">
            <div
              style="
                color: red;
                margin-left: 80px;
                cursor: pointer;
                float: left;
              "
            >
              <a
                href="https://api.map.baidu.com/lbsapi/getpoint/index.html"
                target="_blank"
              >
                帮助链接：获取经纬度
              </a>
            </div>
          </el-col>
        </el-row>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px">
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />
          <div style="display: inline-block; padding-left: 5px">
            是否更新已经存在的数据
          </div>
          <el-button
            type="primary"
            plain
            icon="receiving"
            size="default"
            @click="handleTemplete"
            style="float: right"
            >下载模板</el-button
          >
        </div>
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更多搜索 -->
    <el-drawer
      title="房源搜索"
      v-model="showSearch"
      direction="rtl"
      ref="drawerRef"
    >
      <div class="drawer_content">
        <el-form :model="queryParams" ref="queryMoreFormRef" label-width="80px">
          <el-form-item label="朝向" prop="direction">
            <el-select
              v-model="queryParams.direction"
              placeholder="请选择朝向"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in directionOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="装修" prop="decoration">
            <el-select
              v-model="queryParams.decoration"
              placeholder="请选择装修"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in decorationOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="租金" prop="price">
            <el-input v-model="queryParams.price" placeholder="请输入租金" />
          </el-form-item>
          <el-form-item label="小区名称" prop="villageName">
            <el-select
              v-model="queryParams.villageName"
              placeholder="请选择房源小区"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in houseVillageList"
                :key="index"
                :label="item.name"
                :value="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="房东姓名" prop="ownerName">
            <el-input
              v-model="queryParams.ownerName"
              placeholder="请输入房东姓名"
            />
          </el-form-item>
          <el-form-item label="房东电话" prop="ownerPhone">
            <el-input
              v-model="queryParams.ownerPhone"
              placeholder="请输入房东电话"
            />
          </el-form-item>
        </el-form>
        <div class="drawer_footer">
          <el-button type="primary" size="medium" @click="handleMoreQuery"
            >确定</el-button
          >
        </div>
      </div>
    </el-drawer>

    <select-user ref="select" :ids="ids" @ok="handleQuery" />
    <evaluate ref="evalRef" :id="checkid" />
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, getCurrentInstance, nextTick } from 'vue';
import { listHouseRoom, getHouseRoom, delHouseRoom, addHouseRoom, updateHouseRoom, handleAudit, handlePush, handleClose, handleOpen } from "@/api/house/houseRoom";
import { getToken } from "@/utils/auth";
import { listHouseVillage } from "@/api/house/houseVillage";
import SelectUser from "./selectUser.vue";
import evaluate from "../evaluate/index.vue";

// Data
const data = reactive({
  upload: {
    open: false,
    title: "",
    isUploading: false,
    updateSupport: 0,
    headers: { Authorization: "Bearer " + getToken() },
    url: import.meta.env.VUE_APP_BASE_API + "/system/houseRoom/importData"
  }
})

const { proxy } = getCurrentInstance()
const {upload} = toRefs(data)

const formRef = ref(null)
const queryMoreFormRef = ref(null)
const queryFormRef = ref(null)
const drawerRef = ref(null)
const dataTableRef = ref(null)
const uploadRef = ref(null)
const evalRef = ref(null)

const uploadOpen = ref(true)
const tableHeight = ref(document.documentElement.clientHeight - 180);
const loading = ref(false);
const ids = ref([]);
const checkid = ref(null);
const selection = ref([]);
const single = ref(true);
const multiple = ref(true);
const showSearch = ref(false);
const total = ref(0);
const houseRoomList = ref([]);
const houseVillageList = ref([]);
const title = ref("");
const open = ref(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 20,
  orderByColumn: "create_time",
  isAsc: "desc",
  direction: null,
  decoration: null,
  price: null,
  villageName: null,
  agentName: null,
  agentPhone: null
});
const featureList = ref([]);
const imageList = ref([]);
const form = ref({});
const columns = ref([
  { key: 0, label: `类型`, visible: true },
  { key: 1, label: `户型`, visible: true },
  { key: 2, label: `整套面积`, visible: true },
  { key: 3, label: `出租房间`, visible: true },
  { key: 4, label: `房屋面积`, visible: true },
  { key: 5, label: `朝向`, visible: true },
  { key: 6, label: `装修`, visible: true },
  { key: 7, label: `租金`, visible: true },
  { key: 8, label: `起租日期`, visible: true },
  { key: 9, label: `状态`, visible: true },
  { key: 10, label: `封面图`, visible: true },
  { key: 11, label: `小区名称`, visible: true },
  { key: 12, label: `房牌号`, visible: true },
  { key: 13, label: `门牌号`, visible: true },
  { key: 14, label: `房源代号`, visible: true },
  { key: 15, label: `房东姓名`, visible: true },
  { key: 16, label: `房东电话`, visible: true },
  { key: 17, label: `经纪人`, visible: true },
  { key: 18, label: `经纪人电话`, visible: true },
  { key: 19, label: `备注`, visible: true }
]);
const rules = ref({
  type: [
    {
      required: true,
      message: "请选择类型",
      trigger: "change"
    }
  ],
  houseNum: [
    { required: true, message: "居室不能为空", trigger: "blur" }
  ],
  houseNo: [
    { required: true, message: "房牌号不能为空", trigger: "blur" }
  ],
  decoration: [
    { required: true, message: "装修不能为空", trigger: "blur" }
  ],
  price: [{ required: true, message: "租金不能为空", trigger: "blur" }],
  startDate: [
    { required: true, message: "起租日期不能为空", trigger: "blur" }
  ],
  villageId: [
    { required: true, message: "小区名称不能为空", trigger: "change" }
  ],
  ownerName: [
    { required: true, message: "房东姓名不能为空", trigger: "blur" }
  ],
  owerPhone: [
    { required: true, message: "房东电话不能为空", trigger: "blur" }
  ],
  longitude: [
    { required: true, message: "经度不能为空", trigger: "blur" }
  ],
  latitude: [
    { required: true, message: "纬度不能为空", trigger: "blur" }
  ]
});
const typeOptions = ref([
  { label: "整租", value: 0 },
  { label: "合租", value: 1 }
]);
const houseNumOptions = ref([
  { label: "一室", value: "一室" },
  { label: "二室", value: "二室" },
  { label: "三室", value: "三室" },
  { label: "四室", value: "四室" }
]);
const houseHallOptions = ref([
  { label: "一厅", value: "一厅" },
  { label: "二厅", value: "二厅" }
]);
const toiletNumOptions = ref([
  { label: "一卫", value: "一卫" },
  { label: "二卫", value: "二卫" }
]);
const roomTypeOptions = ref([
  { label: "主卧", value: 1 },
  { label: "次卧", value: 2 }
]);
const directionOptions = ref([
  { label: "东", value: "东" },
  { label: "南", value: "南" },
  { label: "西", value: "西" },
  { label: "北", value: "北" }
]);
const decorationOptions = ref([
  { label: "简装", value: "简装" },
  { label: "中装", value: "中装" },
  { label: "精装修", value: "精装修" },
  { label: "豪装", value: "豪装" }
]);
const stepTypeOptions = ref([
  { label: "电梯房", value: "电梯房" },
  { label: "楼梯房", value: "楼梯房" }
]);

// Methods
const handleCloseHandler = (done) => {
  $confirm("确认关闭？")
      .then((_) => {
        done();
      })
      .catch((_) => {});
};

const changeVillage = (params) => {
  const { value, label } = params;
  form.value.villageName = label;
};

const getVillageList = () => {
  listHouseVillage(queryParams.value).then((response) => {
    houseVillageList.value = response.rows;
  }).catch(err => {
  });
};

const getList = () => {
  loading.value = true;
  listHouseRoom(queryParams.value).then((response) => {
    houseRoomList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(err => {
    loading.value = false;
  });
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value = {
    id: null,
    type: null,
    houseNum: null,
    toiletNum: null,
    houseArea: null,
    roomType: null,
    roomCode: null,
    roomArea: null,
    direction: null,
    price: null,
    floor: null,
    stepType: null,
    startDate: null,
    introduce: null,
    ownerName: null,
    owerPhone: null,
    villageId: null,
    villageName: null,
    address: null,
    houseNo: null,
    payType: null,
    publishId: null,
    state: null,
    createTime: null,
    createName: null,
    updateTime: null,
    updateName: null,
    remark: null,
    houseHall: null,
    code: null,
    faceUrl: null,
    longitude: null,
    latitude: null,
  };
  featureList.value = [];
  imageList.value = [];
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryMoreFormRef.value.resetFields()
  handleQuery();
};

const handleMoreQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
  drawerRef.value.handleClose();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  selection.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  open.value = true;
  title.value = "添加房源";
};

const handleUpdate = (row) => {
  reset();
  const id = row.id || ids.value;
  getHouseRoom(id).then((response) => {
    form.value = response.data;
    form.value.featureList.map((item) => {
      featureList.value.push(item.feature);
    });
    let imageArrary = [];
    form.value.imageList.map((item) => {
      imageArrary.push(item.imagePath);
    });
    imageList.value = imageArrary.join(",");
    open.value = true;
    title.value = "修改房源";
  });
};

const handleAgent = () => {
  $refs.select.show();
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (featureList.value && featureList.value.length > 0) {
        form.value.featureList = featureList.value.map((val) => {
          return { feature: val };
        });
      } else {
        return proxy.$modal.msgWarning("请选择房源亮点");
      }
      if (imageList.value && imageList.value.length) {
        console.log(imageList.value)
        form.value.imageList = imageList.value.split(",").map((val) => {
          return {
            imageName: val.split("/")[6],
            imagePath: val,
            imgUrl: val,
            imageSize: -1,
          };
        });
      } else {
        return proxy.$modal.msgWarning("请选择房源图片");
      }
      if (form.value.id != null) {
        updateHouseRoom(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addHouseRoom(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const ids = row.id || ids.value;
  proxy.$modal
      .confirm("是否确认删除记录？")
      .then(() => delHouseRoom(ids))
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
};

const evalList = (row) => {
  checkid.value = row.id;
  evalRef.value.show(row.id);
};

const handleImport = () => {
  upload.value.title = "房源导入";
  upload.value.open = true;
};

const handleFileUploadProgress = (event, file, fileList) => {
  upload.value.isUploading = true;
};

const handleFileSuccess = (response, file, fileList) => {
  upload.value.open = false;
  upload.value.isUploading = false;
  uploadRef.value.clearFiles();
  proxy.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

const submitFileForm = () => {
  uploadRef.value.submit();
};

const handleTemplete = () => {
  download(
      "system/houseRoom/templete",
      { ...queryParams.value },
      `房源导入模板.xlsx`
  );
};

const handleExport = () => {
  proxy.$confirm("确认导出房源数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    download(
        "system/houseRoom/export",
        { ...queryParams.value },
        `房源_${new Date().getTime()}.xlsx`
    );
  });
};

const typeFormatter = (row, column) => {
  const typeMap = {
    0: "整租",
    1: "合租"
  };

  return typeMap[row.type] || "";
};

const roomTypeFormatter = (row, column) => {
  const roomTypeMap = {
    1: "主卧",
    2: "次卧"
  };

  return roomTypeMap[row.roomType] || "";
};

const stateFormatter = (row, column) => {
  const stateMap = {
    0: "待审核",
    1: "待出租",
    2: "已出租",
    3: "已下架"
  };

  return stateMap[row.state] || "";
};

const handleMoreCommand = (command) => {
  const commandMap = {
    handleAgent: handleAgent,
    handleAudit: handleAuditAction,
    handlePush: handlePushAction,
    handleClose: handleCloseAction,
    handleOpen: handleOpenAction
  };

  const handler = commandMap[command];
  if (handler) {
    handler();
  }
};

const handleImportCommand = (command) => {
  const commandMap = {
    handleImport: handleImport,
    handleTemplete: handleTemplete,
    handleExport: handleExport
  };

  const handler = commandMap[command];
  if (handler) {
    handler();
  }
};

const handleAuditAction = () => {
  const hasMissingAgent = selection.value.some(item => !item.agentUserId);

  if (hasMissingAgent) {
    proxy.$modal.msgWarning("请先设置经纪人");
    return;
  }

  const ids = selection.value.map(item => item.id);

  proxy.$modal.confirm("确认审核房源吗？")
      .then(() => handleAudit(ids))
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("审核成功");
      })
      .catch(() => {});
};

const handlePushAction = () => {
  const ids = ids.value;
  proxy.$modal
      .confirm("确认出租房源吗？")
      .then(() => handlePush(ids))
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("出租成功");
      })
      .catch(() => {});
};

const handleCloseAction = () => {
  const ids = ids.value;
  proxy.$modal
      .confirm("确认下架房源吗？")
      .then(() => handleClose(ids))
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("下架成功");
      })
      .catch(() => {});
};

const handleOpenAction = () => {
  const audited = selection.value.every(item => item.state !== 0);

  if (audited) {
    proxy.$modal
        .confirm("确认上架房源吗？")
        .then(() => {
          handleOpen(ids.value);
          return getList();
        })
        .then(() => proxy.$modal.msgSuccess("上架成功"))
        .catch(() => {});
  } else {
    proxy.$modal.msgWarning("请先审核房源");
  }
};

const setDataTable = () => {
  nextTick(() => {
    dataTableRef.value.doLayout();
  });
};
getList()
getVillageList()
</script>

<style lang="scss" scoped>
.drawer_content {
  margin: 0 30px;
  .drawer_footer {
    float: right;
    padding-bottom: 40rpx;
  }
}
</style>
